<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="/mapi/upload/avatar"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :headers="headers"
      :disabled="disabled"
    >
      <img
        v-if="imageUrl"
        :src="imageUrl"
        class="avatar"
      >
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
      />
      <span
        v-if="imageUrl"
        class="el-upload-list__item-preview"
        style="position: absolute; left: 120%; z-index: 10000; bottom: -5px;"
        @click.stop="handlePictureCardPreview"
      >
        <i class="el-icon-zoom-in" />
      </span>
    </el-upload>

    <el-dialog
      :visible.sync="dialogVisible"
      append-to-body
      width="20%"
    >
      <img
        width="100%"
        :src="imageUrl"
        alt=""
      >
    </el-dialog>

  </div>
</template>
<script>
import { getToken } from '@/utils/auth' // get token from cookie
export default {
  name: 'Upload',
  props: {
    imgUrl: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // imageUrl: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
      // dialogImageUrl: '',
      imageUrl: this.imgUrl,
      dialogVisible: false,
      headers: {
        'ticket': getToken()
      }
    }
  },
  watch: {
    imgUrl(val) {
      this.imageUrl = val
    }
  },
  methods: {
    onSuccess(res, file, fileList) {
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      const oldImageUrl = this.imageUrl
      this.imageUrl = res.data
      this.$emit('on-success', this.imageUrl, oldImageUrl)
    },
    beforeAvatarUpload(file) {
      const reg = /\.jpg$|\.jpeg$|\.png$/i
      const fileType = reg.test(file.name)
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!fileType) {
        this.$message.error('图片格式不正确!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return fileType && isLt2M
    },
    handlePictureCardPreview() {
      // this.dialogImageUrl = this.imageUrl;
      this.dialogVisible = true
    }

  }
}
</script>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
  line-height: 22px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 36px;
  height: 36px;
  line-height: 36px;
  text-align: center;
}
.avatar {
  width: 36px;
  height: 36px;
  display: block;
}
</style>
